#include "MapperUxROM.h"
#include "Log.h"

PNE_NAMESPACE_BEGIN

MapperUxROM::MapperUxROM(Cartridge &cart)
    : Mapper(cart, Mapper::Type::UxROM),
      m_selectPRG(0)
{
    if (cart.GetVROM().size() == 0)
    {
        m_usesCharacterRAM = true;
        m_characterRAM.resize(0x2000);
        LOG(Level::Info) << "Uses character RAM" << std::endl;
    }
    else
        m_usesCharacterRAM = false;
    // last - 16KB
    m_lastBankPtr = &cart.GetROM()[cart.GetROM().size() - 0x4000];
}

Byte MapperUxROM::ReadPRG(Address addr)
{
    if (addr < 0xc000)
        return m_cartridge.GetROM()[((addr - 0x8000) & 0x3fff) | (m_selectPRG << 14)];
    else
        return *(m_lastBankPtr + (addr & 0x3fff));
}

void MapperUxROM::WritePRG(Address addr, Byte value)
{
    m_selectPRG = value;
}

Byte MapperUxROM::ReadCHR(Address addr)
{
    if (m_usesCharacterRAM)
        return m_characterRAM[addr];
    else
        return m_cartridge.GetVROM()[addr];
}

void MapperUxROM::WriteCHR(Address addr, Byte value)
{
    if (m_usesCharacterRAM)
        m_characterRAM[addr] = value;
    else
        LOG(Level::Info) << "Read-only CHR memory write attempt at " << std::hex
                         << addr << std::endl;
}

PNE_NAMESPACE_END
// DONE